package com.xu.sms.db;

import java.util.ArrayList;
import java.util.List;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.xu.sms.entity.SHistory;

public class SHistoryDao {
	
	private MySqliteOpenHelper msoh;
	
	public SHistoryDao(MySqliteOpenHelper msoh){
		this.msoh = msoh;
	}
	
	/*
	 * 1.插入记录
	 * 2.删除记录
	 * 3.查询所有
	 * 4.删除所有
	 */
	public void insert(String keyword){
		SQLiteDatabase db = msoh.getReadableDatabase();
		String sql="insert into t_shistory(keyword) values(?)";
		Object[] bindArgs = {keyword};
		db.execSQL(sql, bindArgs);
		close(db,null);
	}
	
	public void delete(int id){
		SQLiteDatabase db = msoh.getReadableDatabase();
		String sql = "delete from t_shistory where _id = ?";
		Object[] bindArgs = {id};
		db.execSQL(sql, bindArgs);
		close(db,null);
	}
	
	public void delAll(){
		SQLiteDatabase db = msoh.getReadableDatabase();
		String sql = "delete from t_shistory";
		db.execSQL(sql);
		close(db,null);
		updateSqliteSequence();
		
	}
	
	public void updateSqliteSequence(){
		String sql = "update sqlite_sequence SET seq = 0 where name = ? ";
		SQLiteDatabase db = msoh.getReadableDatabase();
		db.execSQL(sql,new Object[]{"t_shistory"});
		close(db,null);
	}
	
	public List<SHistory> findAll(){
		SQLiteDatabase db = msoh.getReadableDatabase();
		List<SHistory> shList = new ArrayList<SHistory>();
		String sql = "select * from t_shistory order by _id desc";
		Cursor cursor = db.rawQuery(sql, null);
		if(cursor !=null && cursor.getCount() >0){
			while(cursor.moveToNext()){
				int _id = cursor.getInt(0);
				String keyword = cursor.getString(1);
				shList.add(new SHistory(_id, keyword));
			}
		}
		return shList;
	}
	public void close(SQLiteDatabase db,Cursor cursor){
		
		if(cursor !=null){
			cursor.close();
		}
		if(db !=null){
			db.close();
		}
	}

}
